//
//  LDYStatusOriginaView.swift
//  李东阳微博
//
//  Created by 李东阳 on 16/4/21.
//  Copyright © 2016年 李东阳. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit
class LDYStatusOriginaView: UIView {

    // 记录我们原创微博的底部约束
    var originalViewBottomConstraint: Constraint?
    
    var status:LDYStatus?{
            didSet{
                
             "TODO:|FIXME: 原创微博*********************"        
                //MARK: -  用户头像
            headImageView.sd_setImageWithURL( NSURL(string:  status?.user?.profile_image_url ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
            
                //MARK: -  昵称
            nameLabel.text = status?.user?.screen_name
                //MARK: -  会员等级
            mbrankImageView.image = getmbrankImage(status?.user?.mbrank ?? 0)
            
                //MARK: -  时间
            timeLabel.text = getWeiboTimeString((status?.created_at)!)

                //MARK: -  来源
//            sourceLabel.text = "李东阳大老爷"
            sourceLabel.attributedText = getSourceString(status?.source)
                //MARK: -  认证
            verifiedView.image = getverifiedImage(status?.user?.verified_type ?? -1)
            
                //MARK: -  微博正文
            contentLabel.text = status?.text
//                //MARK: -  传值配图
//            statusPicView.picInfo = status?.pic_urls
                
             self.originalViewBottomConstraint?.uninstall()
                
            "TODO:|FIXME: 判断有没有配图 时间 和 来源 "
                if status?.pic_urls?.count != 0{
                
                 statusPicView.picInfo = status?.pic_urls
                    
                self.snp_makeConstraints(closure: { (make) -> Void in
                
                  self.originalViewBottomConstraint =  make.bottom.equalTo(statusPicView.snp_bottom).offset(10).constraint
                    
                  statusPicView.hidden = false
                })
                    
                }else{
                    self.snp_makeConstraints(closure: { (make) -> Void in
                        
                self.originalViewBottomConstraint = make.bottom.equalTo(contentLabel.snp_bottom).offset(10).constraint
                    })
                
                      statusPicView.hidden = true
                }
                

        }
    
    }
    
    
    //Mark: - 处理微博来源字符串
    func getSourceString( source: String? ) -> NSMutableAttributedString{
    
            //MARK: -  判断我们的来源字符串是否存在 且包含"\">"

        guard let str  = source where str.containsString("\">") else{
        
        return NSMutableAttributedString(string: "")
            
        }
        
        let startRange = str.rangeOfString("\">")!
        let endRange = str.rangeOfString("</a")!
        
        let result = str.substringWithRange(startRange.endIndex..<(endRange.startIndex) )
       
        //拼接后最终显示的结果
        let name = "来自\(result)"
        
        let attr = NSMutableAttributedString(string: name)
        
        let ran = (name as NSString).rangeOfString("来自")
            //MARK: -  通过富文本更改富文本的属性

        attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.grayColor(), range: ran)
        
        return attr
    
    }

    
    // 认证图片逻辑处理
    /// 认证类型，-1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
    func  getverifiedImage(verified: Int) -> UIImage?{
    
        switch verified{
        
        case 0:
            return  UIImage(named: "avatar_vip")
        case 2,3,5:
            return  UIImage(named: "avatar_enterprise_vip")
        case 220:
            return  UIImage(named: "avatar_grassroot")
        default:
            return nil
        }
    
    }
    
    //MARK: - 处理时间逻辑
    func getWeiboTimeString(weiboTime: String) -> String{
    
    let myMatter = NSDateFormatter()
        
     //设置格式
    myMatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
    
    //设置locale
    myMatter.locale = NSLocale(localeIdentifier: "en_US")
    
    
        //获取微博date
    let weiboDate = myMatter.dateFromString(weiboTime)!
    
//   //测试
//      let weiboDate = weiboDate1.dateByAddingTimeInterval(-3600 * 24 * 900)
        
        //获取微博 对比
      let isTHisYear  = weiboTimeIsThisYear(weiboDate)
        
        if !isTHisYear{
        
            myMatter.dateFormat = "yyyy年MM月dd日 HH:mm"
            
            return myMatter.stringFromDate(weiboDate)
            
        }else{
           
            let calendar = NSCalendar.currentCalendar()
            
            //判断是今天
            if  calendar.isDateInToday(weiboDate){
            
              
              let s = NSDate().timeIntervalSinceDate(weiboDate)
                
                if s < 60 {
                //如果 < 60 s 显示格式 : 刚刚
                    
                  return "刚刚"
                }else if s >= 60 && s < 3600 {
                //如果 >=60 && < 60 * 60 显示格式:xx分钟前
                
                    return "\(Int(s/60))分钟前"
                }else{
                //其它显示格式: xx小时之前
                
                return "\(Int(s/3600))小时前"
                }
    
        
            }else if calendar.isDateInYesterday(weiboDate) {
            
                myMatter.dateFormat = "昨天 HH:mm"
                
                return myMatter.stringFromDate(weiboDate)
            }else{
            
              myMatter.dateFormat = "MM月dd日 HH:mm"
                
             return myMatter.stringFromDate(weiboDate)
            }
            
        }

    }
    
    //MARK: - 判断是否是今年
    func   weiboTimeIsThisYear(weibodate: NSDate) -> Bool{
    
    let  myMatter = NSDateFormatter()
        
    //设置格式
        myMatter.dateFormat = "yyyy"
    
        myMatter.locale = NSLocale(localeIdentifier: "en_us")
    
       //得到微博时间的年的字符串
        let weiboStr = myMatter.stringFromDate(weibodate)
        
        //当前时间年的字符串
       let currentStr = myMatter.stringFromDate(NSDate())
        
       //如果微博的年的字符串和当前的时间年的字符串一样  就代表是今年
        if weiboStr == currentStr{
        
            return true
        }else{
        
           return false
        }
    }
    
    //MARK: - 会员等级

    func getmbrankImage(mbrank: Int) -> UIImage?{
        if mbrank > 0 && mbrank < 7{
        
            return UIImage(named: "common_icon_membership_level\(mbrank)")
        }else{
        
        return UIImage(named:"common_icon_membership_expired")
        }
    
        
    }
    
    override init(frame: CGRect) {
        //Mark --
        
        super.init(frame: frame)
        
        setupUI()

    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
        //MARK: -  设置视图
    private func setupUI(){
    
         //MARK: -  添加控件
    self.backgroundColor =  UIColor.whiteColor()
        addSubview(headImageView)
        addSubview(nameLabel)
        addSubview(mbrankImageView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(verifiedView)
        addSubview(contentLabel)
        addSubview(statusPicView)
        
        
            //MARK: -  设置约束   用户头像01================
    headImageView.snp_makeConstraints { (make) -> Void in
    make.top.leading.equalTo(10)
    make.size.equalTo(CGSize(width: 35, height: 35))
        }
        
        
            //MARK: -  用户昵称 02 ====================
    nameLabel.snp_makeConstraints { (make) -> Void in
        make.top.equalTo(10)
        make.leading.equalTo(headImageView.snp_trailing).offset(10)
        }
            //MARK: -  会员图片 03 =================
    mbrankImageView.snp_makeConstraints { (make) -> Void in
      make.leading.equalTo(nameLabel.snp_trailing).offset(10)
      make.centerY.equalTo(nameLabel)
        }
    
            //MARK: -  时间 04 ===================
        timeLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(headImageView.snp_trailing).offset(10)
            make.bottom.equalTo(headImageView)
        }

            //MARK: -  来源 05================
        sourceLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(timeLabel.snp_trailing).offset(10)
             make.bottom.equalTo(timeLabel)
        }
            //MARK: -  06 认证 06 ================
        verifiedView.snp_makeConstraints { (make) -> Void in
             make.centerX.equalTo(headImageView.snp_trailing)
             make.centerY.equalTo(headImageView.snp_bottom)
        }
            //MARK: -   07 微博正文 =================
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(10)
            make.top.equalTo(headImageView.snp_bottom).offset(10)
            make.width.equalTo(UIScreeonwidth - 20)
        }
        
               //MARK: -  08 配图 =================
        statusPicView.snp_makeConstraints { (make) -> Void in
            
            "TODO:|FIXME: frame 已经在配图view里面处理"
//            make.size.equalTo(CGSize(width: 100, height: 100))
            make.top.equalTo(contentLabel.snp_bottom).offset(10)
            make.leading.equalTo(contentLabel)
            
            
        }
        

    self.snp_makeConstraints { (make) -> Void in
           self.originalViewBottomConstraint = make.bottom.equalTo(statusPicView).offset(10).constraint
        
        }

    }
    

        //MARK: -  懒加载控件
        //MARK: - 用户头像
    private  lazy var headImageView:UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
        //MARK: -  用户昵称
    private lazy var nameLabel:UILabel = UILabel(textColor: UIColor.darkTextColor(), textFont: 14)
    
        //MARK: -  会员等级
    private lazy var mbrankImageView:UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
    
        //MARK: -  时间
    private lazy var timeLabel :UILabel = UILabel(textColor: myTintColor, textFont: 10)
    
        //MARK: -  来自哪里
    private lazy var  sourceLabel:UILabel =  UILabel(textColor: myTintColor, textFont: 10)
    
        //MARK: -  认证
    private lazy var verifiedView:UIImageView = UIImageView(image: UIImage(named: "avatar_vgirl"))
    
        //MARK: -  微博正文
    private lazy var contentLabel:UILabel = {
        let lab = UILabel(textColor: UIColor.blackColor(), textFont: 14)
        
        lab.numberOfLines = 0
        return lab
        }()
    
        //MARK: -  配图view
    private lazy var statusPicView:LDYstatusPictureView = LDYstatusPictureView()
    
    
    
    
    

}
